﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using RXY_Mall.Core.Tool;

namespace RXY_Mall.Core
{
    /// <summary>
    /// Writter：Scenery
    /// Desc：用于记录日志
    /// Date：2012-12-11
    /// </summary>
    public class LogHelper
    {
        private static LogHelper instance = null;

        /// <summary>
        /// 获取实例 Scenery 2012-12-11
        /// </summary>
        /// <returns></returns>
        public static LogHelper GetInstance()
        {
            if (instance == null)
            {
                instance = new LogHelper();
            }
            return instance;
        }

        /// <summary>
        /// 删除两月前的日志记录  Scenery 2012-12-11
        /// </summary>
        public static bool DeleteLogAndError(string filePath)
        {
            bool flag = true;
            try
            {
                if (Directory.Exists(filePath))
                {
                    string[] fileRar = Directory.GetFileSystemEntries(filePath);
                    if (fileRar.Length > 0)
                    {
                        DateTime createTime;
                        DateTime time = DateTime.Now.AddMonths(-3);
                        for (int i = 0; i < fileRar.Length; i++)
                        {
                            string path = fileRar[i];
                            createTime = DateTime.Parse(Path.GetFileNameWithoutExtension(fileRar[i]));
                            if (createTime < time)
                            {
                                if (Directory.Exists(path))
                                {
                                    Directory.Delete(path, true);//删除目录
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 创建日志目录及日志文件
        /// </summary>
        /// <param name="name">日志文件夹</param>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        public static void CreateDirectory(string name)
        {
            if (name != "")
            {
                // 创建日志文件夹
                string path = CommonHelper.GetRootPath + @"\\" + name + "\\";
                if (!Directory.Exists(path))
                {
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch (Exception)
                    {

                    }
                }
                //创建月份命名的文件夹
                string path1 = path + DateTime.Now.ToString("yyyy-MM") + "\\";
                if (!Directory.Exists(path1))
                {
                    try
                    {
                        Directory.CreateDirectory(path1);
                    }
                    catch (Exception)
                    {

                    }
                }
                // 创建日志文件
                string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                string filePath = path1 + fileName;
                if (!File.Exists(filePath))
                {
                    try
                    {
                        FileStream file = File.Create(filePath);
                        file.Close();
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        /// <summary>
        /// 一般日志记录
        /// </summary>
        /// <param name="logInfo">需要记录的日志信息</param>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        public static void WriteLog(string logInfo)
        {
            GetInstance();

            try
            {
                lock (instance)
                {
                    if (!string.IsNullOrEmpty(logInfo))
                    {
                        CreateDirectory("Log");

                        // 日志文件夹路径
                        string path = CommonHelper.GetRootPath + @"\Log\" + DateTime.Now.ToString("yyyy-MM") + "\\";

                        // 日志文件路径
                        string filePath = path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                        // 记录日志
                        using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                        {
                            StringBuilder sbStr = new StringBuilder();
                            sbStr.Append("-------------------------------------------------------------------------");
                            sbStr.Append("\r\n");
                            sbStr.Append("日期：" + DateTime.Now.ToString());
                            sbStr.Append("\r\n");
                            sbStr.Append("日志记录：" + logInfo);
                            sbStr.Append("\r\n");

                            sw.Write(sbStr.ToString());
                            sw.Flush();
                        }
                    }
                }
            }
            catch (Exception)
            {
                
            }
        }

        /// <summary>
        /// 异常日志记录
        /// </summary>
        /// <param name="currentEx">当前发生的异常</param>
        /// <param name="methodName">方法名称</param>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        public static void WriteLog(Exception currentEx)
        {
            GetInstance();

            try
            {
                lock (instance)
                {
                    if (currentEx != null)
                    {
                        CreateDirectory("Error");

                        // 日志文件夹路径
                        string path = CommonHelper.GetRootPath + @"\Error\" + DateTime.Now.ToString("yyyy-MM") + "\\";
                        // 日志文件路径
                        string filePath = path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                        // 记录日志
                        using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                        {
                            StringBuilder sbStr = new StringBuilder();
                            sbStr.Append("趣+电商");
                            sbStr.AppendLine("-------------------------------------------------------------------------");
                            sbStr.AppendLine("错误发生时间：" + DateTime.Now.ToString());
                            sbStr.AppendLine("错误信息：" + currentEx.Message.ToString());
                            sbStr.AppendLine("错误源：" + currentEx.StackTrace.ToString());

                            sw.Write(sbStr.ToString());
                            sw.Flush();
                        }
                    }
                }
                Task.Run(() => { EmailHelper.SendEmail("趣+电商异常错误", currentEx); });
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 异常日志记录
        /// </summary>
        /// <param name="currentEx">当前发生的异常</param>
        /// <param name="errorUrl">同步错误Url</param>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        public static void WriteLog(Exception currentEx, string errorUrl)
        {
            GetInstance();

            try
            {
                lock (instance)
                {
                    if (currentEx != null)
                    {
                        CreateDirectory("Error");

                        // 日志文件夹路径
                        string path = CommonHelper.GetRootPath + @"\Error\" + DateTime.Now.ToString("yyyy-MM") + "\\";

                        // 日志文件路径
                        string filePath = path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                        // 记录日志
                        using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                        {
                            StringBuilder sbStr = new StringBuilder();
                            sbStr.Append("趣+电商");
                            sbStr.AppendLine("-------------------------------------------------------------------------");
                            sbStr.AppendLine("错误发生时间：" + DateTime.Now.ToString());
                            sbStr.AppendLine("错误信息：" + currentEx.Message.ToString());
                            sbStr.Append("错误源：" + currentEx.StackTrace.ToString());
                            sbStr.AppendLine("同步Url：" + errorUrl);

                            sw.Write(sbStr.ToString());
                            sw.Flush();
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }
    }
}
